package com.zl.zlproject.model.net.engine;


import com.zl.zlproject.BuildConfig;
import com.zl.zlproject.base.application.MyApplication;
import com.zl.zlproject.model.net.api.AppUrl;
import com.zl.zlproject.model.net.engine.intercepter.FilterFastRequestInterceptor;
import com.zl.zlproject.model.net.engine.intercepter.ForceCacheInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 郑磊 on 2018/5/29.
 */

public class RetrofitHelper {
    /**
     * 缓存的默认大小
     */
    private static final int DEFAULT_CACHE_SIZE = 1024 * 1024 * 15; //15M

    /**
     * 缓存的默认文件夹
     */
    private static final String DEFAULT_CACHE_FILE = "okhttp_cache";

    private static final int TIME_OUT = 5;  //超时设置

    private static OkHttpClient mOkhttpClient;



    /**
     * 私有构造方法
     *
     *
     */
    private RetrofitHelper() {}


    /**
     * 获取retrofit
     */

    private static Retrofit getRetrofit(String baseUrl) {
        if (mOkhttpClient == null) {
            getOkhttpClient();
        }
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())    //gson 解析
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mOkhttpClient)
                .baseUrl(baseUrl)
                .build();
    }





    /**
     * 构建okhttpClient
     */
    private static void getOkhttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS) //连接超时
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)  //读取超时

                .addInterceptor(new ForceCacheInterceptor(MyApplication.getContext()))  //没有网络，加载缓存
                //过滤频繁请求，10为缓存时间，单位秒,10秒之内反复请求，取缓存，超出10秒，取服务器数据
                .addNetworkInterceptor(new FilterFastRequestInterceptor(10))
                .cache(new Cache(new File(MyApplication.getContext().getCacheDir(), DEFAULT_CACHE_FILE), DEFAULT_CACHE_SIZE));//设置缓存目录及大小
        if (BuildConfig.DEBUG) {  //如果是debug  就打印网络参数
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        mOkhttpClient = builder.build();
    }

    public static  <K>K creatApi(Class<K> clazz,String baseUrl){
        return RetrofitHelper.getRetrofit(baseUrl ==null ? AppUrl.getHttpUrl() :baseUrl).create(clazz);
    }
    public static  <K>K creatApi(Class<K> clazz){
        return creatApi(clazz,null);
    }




}
